const fs = require('fs');
const path = require('path');
const tinify = require('tinify');

// 请在运行前设置环境变量 TINYPNG_API_KEY 或直接在此处填写
const apiKey = process.env.TINYPNG_API_KEY || process.env.TINIFY_KEY || '';
if (!apiKey) {
  console.error('未检测到 TinyPNG API Key。请设置环境变量 TINYPNG_API_KEY 后再运行。');
  process.exit(1);
}

tinify.key = apiKey;

const targets = [
  path.resolve(__dirname, 'miniprogram/assets/customer-service/qr_code.png'),
  path.resolve(__dirname, 'miniprogram/pages/pay/assets/order/background_top.png')
];

(async () => {
  for (const file of targets) {
    if (!fs.existsSync(file)) {
      console.warn(`[跳过] 未找到文件: ${file}`);
      continue;
    }
    const backup = `${file}.bak`;
    fs.copyFileSync(file, backup);
    console.log(`[备份完成] ${backup}`);
    try {
      const source = tinify.fromFile(file);
      await source.toFile(file);
      console.log(`[压缩成功] ${file}`);
    } catch (err) {
      console.error(`[压缩失败] ${file}`, err.message || err);
    }
  }
})();